//
//  CYHttps.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/8/10.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYHttps.h"
#import "CYHUD.h"
@interface CYHttps()
@property (nonatomic, strong) CYHUD *hud;
@end
@implementation CYHttps
static  CYHttps*_httpsManager;
static dispatch_once_t onceToken;
+ (instancetype)shareCYHttpsManager{
    if (!_httpsManager) {
        dispatch_once(&onceToken, ^{
            _httpsManager = [[CYHttps alloc]initWithBaseURL:[NSURL URLWithString:IP]];
            _httpsManager.responseSerializer = [AFHTTPResponseSerializer serializer];//设置接受到的数据格式
            _httpsManager.requestSerializer = [AFHTTPRequestSerializer serializer];//设置请求数据的格式
            [_httpsManager.requestSerializer setValue:@"token" forHTTPHeaderField:@"token"];
            _httpsManager.requestSerializer.timeoutInterval = 10.0f;//设置超时
        });
    }
    return _httpsManager;
}

//把菊花设置为https的属性，确保页面切换时候，只有一个hud的内容模式来回变换，而不会出现多个hud叠加,***注意，这个hud时加载在window上，隐藏时候，不从父视图移除
- (CYHUD *)hud{
    if (!_hud) {
        _hud = [CYHUD hud];
    }
    _hud.mode = MBProgressHUDModeIndeterminate;
    _hud.label.text = nil;
    if (!_hud.superview)
        [_hud addToWindow];
    return _hud;
}

- (void)setNetwork:(BOOL)network{
    if (_network != network) {
        _network = network;
        if (!network) {
            self.WWANNetwork = network;
            self.WiFiNetwork = network;
            self.unknowmNetwork = network;
        }
    }
}

- (void)setUnknowmNetwork:(BOOL)unknowmNetwork{
    if (_unknowmNetwork != unknowmNetwork) {
        _unknowmNetwork = unknowmNetwork;
        if (unknowmNetwork)
            self.network = YES;
    }
}


- (void)setWWANNetwork:(BOOL)WWANNetwork{
    if (_WWANNetwork != WWANNetwork) {
        _WWANNetwork = WWANNetwork;
        if (WWANNetwork)
            self.network = YES;
    }
}

- (void)setWiFiNetwork:(BOOL)WiFiNetwork{
    if (_WiFiNetwork != WiFiNetwork) {
        _WiFiNetwork = WiFiNetwork;
        if (WiFiNetwork)
            self.network = YES;
    }
}
//检测网络
+ (void)checkNetwork{
    
    CYHttps *_cyHttpsManager = [self shareCYHttpsManager];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == 1)
            _cyHttpsManager.WWANNetwork = YES;
        else if (status == 2)
            _cyHttpsManager.WiFiNetwork = YES;
        else if (status == -1 || status == 0){
            _cyHttpsManager.network = NO;
            [CYHUD show:@"网络断开链接"];
        }
    }];
}

+ (NSURLSessionTask *)POST:(NSString *)API parameters:(id)dict success:(success)success failure:(failure)fail{
    CYHttps *httpsManager = [self shareCYHttpsManager];
    
    NSURLSessionDataTask * task = [httpsManager POST:API parameters:dict progress:nil
                                             success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                                 
                                                 dispatch_async(dispatch_get_main_queue(), ^{
                                                     NSDictionary *data =  [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                                                     if (data[@"data"])
                                                         success(data[@"data"]);
                                                     else if(data[@"Data"])
                                                         success(data[@"Data"]);
                                                 });
                                             }
                                             failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                                 NSDictionary *error_data = [error userInfo];//获取失败信息
                                                 NSString *errorStr = error_data[@"NSLocalizedDescription"];
                                                 
                                                 if (errorStr){//如果请求失败，
                                                     if (fail)
                                                         fail(errorStr);
                                                 }
                                             }];
    return task;
    
    
}

//post
+ (NSURLSessionTask *)POST:(NSString *)API parameters:(id)dict showHUD:(BOOL)show progress:(progress)block_progress success:(success)success failure:(failure)fail{
    
    //构造manager
    CYHttps *httpsManager = [self shareCYHttpsManager];
    
    //状态栏显示菊花
    UIApplication *application = [UIApplication sharedApplication];
    application.networkActivityIndicatorVisible = YES;
    
    //显示自定义菊花
    [httpsManager.hud showAnimated:YES];
    if (!show)
        [httpsManager.hud hideAnimated:NO];
    
    //post请求
    NSURLSessionDataTask *task = [httpsManager POST:API parameters:dict
                                           progress:^(NSProgress * _Nonnull uploadProgress) {
                                               if (block_progress)
                                                   block_progress(uploadProgress);
                                           }
                                            success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                                
                                                //请求成功，隐藏状态栏的菊花
                                                UIApplication *application = [UIApplication sharedApplication];
                                                application.networkActivityIndicatorVisible = NO;
                                                
                                                //请求成功，隐藏自定义菊花
                                                [httpsManager.hud hideAnimated:YES];
                                                
                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                    
                                                    NSDictionary *data =  [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                                                    
                                                    //参数正确，并且请求成功
                                                    if ([data[@"code"] integerValue] == 1 && data[@"data"] != [NSNull null])
                                                        success(data[@"data"]);
                                                    
                                                    //token过期
                                                    else if ([data[@"code"] integerValue] == 2)
                                                        [httpsManager.hud show:data[@"message"] complete:^(NSString *status) {//则弹出文本提示
                                                            success(data[@"code"]);
                                                        }];
                                                    
                                                    //参数失败，请求成功
                                                    else {
                                                        if (data[@"message"] && show)//如果message有值，
                                                            [CYHUD show:data[@"message"]];
                                                        else
                                                            success(nil);
                                                    }
                                                    //                                                                 }];
                                                });
                                            }
                                            failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                                
                                                //请求成功，隐藏状态栏的菊花
                                                UIApplication *application = [UIApplication sharedApplication];
                                                application.networkActivityIndicatorVisible = NO;
                                                
                                                //请求成功，隐藏自定义菊花
                                                [httpsManager.hud hideAnimated:YES];
                                                
                                                //网络请求取消
                                                if (task.error.code == NSURLErrorCancelled){
                                                }
                                                
                                                //其他失败错误
                                                else
                                                    dispatch_async(dispatch_get_main_queue(), ^{
                                                        
                                                        NSDictionary *error_data = [error userInfo];//获取失败信息
                                                        NSString *errorStr = error_data[@"NSLocalizedDescription"];
                                                        
                                                        if (errorStr){//如果请求失败，
                                                            if (httpsManager.network)//如果有网络
                                                                [httpsManager.hud show:errorStr complete:^(NSString *status) {//则弹出文本失败提示
                                                                    if (fail)
                                                                        fail(errorStr);
                                                                }];
                                                            else{//如果没有网络
                                                                if (fail)
                                                                    fail(errorStr);
                                                            }
                                                        }
                                                    });
                                            }];
    return task;
}

//get
+ (NSURLSessionTask *)GET:(NSString *)API parameters:(NSDictionary *)dict  showHUD:(BOOL)show progress:(progress)block_progress success:(success)success failure:(failure)fail{
    
    CYHttps *httpsManager = [self shareCYHttpsManager];
    
    //状态栏显示菊花
    UIApplication *application = [UIApplication sharedApplication];
    application.networkActivityIndicatorVisible = YES;
    
    //显示自定义菊花
    [httpsManager.hud showAnimated:YES];
    if (!show)
        [httpsManager.hud hideAnimated:NO];
    
    //get请求
    NSURLSessionDataTask *task = [httpsManager GET:API parameters:dict
                                          progress:^(NSProgress * _Nonnull downloadProgress) {
                                              
                                          }
                                           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                               
                                               //请求成功，隐藏状态栏的菊花
                                               UIApplication *application = [UIApplication sharedApplication];
                                               application.networkActivityIndicatorVisible = NO;
                                               
                                               //请求成功，隐藏自定义菊花
                                               [httpsManager.hud hideAnimated:YES];
                                               
                                               dispatch_async(dispatch_get_main_queue(), ^{
                                                   
                                                   NSDictionary *data =  [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                                                   
                                                   if ([data[@"code"] integerValue] == 1 && data[@"data"] != [NSNull null]) //参数正确，并且请求成功
                                                       success(data[@"data"]);
                                                   
                                                   else if ([data[@"code"] integerValue] == 0){ //参数失败，请求成功
                                                       if (data[@"message"] && show)//如果message有值，
                                                           [httpsManager.hud show:data[@"message"] complete:^(NSString *status) {//则弹出文本提示
                                                               success(nil);
                                                           }];
                                                       else
                                                           success(nil);
                                                   }
                                               });
                                           }
                                  
                                           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                               
                                               //请求成功，隐藏状态栏的菊花
                                               UIApplication *application = [UIApplication sharedApplication];
                                               application.networkActivityIndicatorVisible = NO;
                                               
                                               //请求成功，隐藏自定义菊花
                                               [httpsManager.hud hideAnimated:YES];
                                               
                                               if (task.error.code == NSURLErrorCancelled){ //网络请求取消
                                               }
                                               else
                                                   dispatch_async(dispatch_get_main_queue(), ^{
                                                       
                                                       NSDictionary *error_data = [error userInfo];//获取失败信息
                                                       NSString *errorStr = error_data[@"NSLocalizedDescription"];
                                                       
                                                       if (errorStr){//如果请求失败，
                                                           if (httpsManager.network)//如果有网络
                                                               [httpsManager.hud show:errorStr complete:^(NSString *status) {//则弹出文本失败提示
                                                                   if (fail)
                                                                       fail(errorStr);
                                                               }];
                                                           else{//如果没有网络
                                                               if (fail)
                                                                   fail(errorStr);
                                                           }
                                                       }
                                                   });
                                           }];
    return task;
}

//从url异步并发加载图片
+ (void)loadingWithFile:(NSString *)file complete:(void(^)(id data))complete{
    if (!file)
        return;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *path = [NSString stringWithFormat:@"%@%@",IP,file];
        NSURL *url = [NSURL URLWithString:path];
        NSData *data = [NSData dataWithContentsOfURL:url];
        if (data){
            dispatch_async(dispatch_get_main_queue(), ^{
                complete([UIImage imageWithData:data]);
            });
            
        }
    });
}
@end
